package com.csaba.connector.web.util;

import java.io.InputStream;
import java.security.KeyStore;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import com.csaba.util.LoggerHelper;

public class NetLockCertificate
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	public static SSLContext installCert()
	{
		try
		{

			String fileName = "netlockclassb";
			if ( System.getProperty("java.vendor").contains("Android") )
				fileName = "netlockclassb.bks";
			final InputStream stream = NetLockCertificate.class.getResourceAsStream(fileName);
			final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
			ks.load(stream, "changeit".toCharArray());
			stream.close();

			final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			tmf.init(ks);

			final SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, tmf.getTrustManagers(), null);

			return sslContext;
		}
		catch ( final Exception ex )
		{
			logger.log(Level.SEVERE, "Error initializing certificate store.", ex);
		}
		return null;
	}

}
